package services

import (
	"irisfarm/app/commons/auth"
	"irisfarm/app/models"
	"irisfarm/app/repositories"
	"strconv"
	"time"

	"github.com/iris-contrib/middleware/jwt"
	"github.com/kataras/iris/v12"
	"github.com/spf13/viper"
)

type UserServer struct {
	BaseServer
}

func (u *UserServer) Register(ctx iris.Context) (map[string]string, error) {

	authRepository := repositories.AuthRepository{}
	userModel, err := authRepository.GoRegister(ctx)
	if err != nil {
		return nil, err
	}

	tokenString, err := u.genToken(userModel)
	if err != nil {
		return nil, err
	}

	returnData := make(map[string]string)
	returnData["uid"] = strconv.Itoa(int(userModel.ID))
	returnData["username"] = userModel.Username
	returnData["token"] = tokenString

	return returnData, nil
}

// Login 登录
func (u *UserServer) Login(ctx iris.Context) (map[string]string, error) {
	// 获取用户信息
	authRepository := repositories.AuthRepository{}
	userModel, err := authRepository.GetByUsername(ctx)
	if err != nil {
		return nil, err
	}

	tokenString, err := u.genToken(userModel)
	if err != nil {
		return nil, err
	}

	returnData := make(map[string]string)
	returnData["uid"] = strconv.Itoa(int(userModel.ID))
	returnData["username"] = userModel.Username
	returnData["token"] = tokenString

	return returnData, nil
}

func (u *UserServer) genToken(userModel models.UsersModel) (string, error) {
	token := jwt.NewTokenWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"uid":         strconv.Itoa(int(userModel.ID)),
		"username":    userModel.Username,
		"time":        time.Now(),
		"expire_time": time.Hour * 24 * 30,
	})

	// Sign and get the complete encoded token as a string using the secret
	tokenString, err := token.SignedString([]byte(viper.GetString("app.key")))
	if err != nil {
		return "", err
	}

	return tokenString, nil
}

// Logout 退出登录
func (u *UserServer) Logout(ctx iris.Context) (map[string]interface{}, error) {
	// 使用的jwt，没法退出登录，退出登录的时候不需要调用服务器接口
	user, _ := auth.User(ctx)

	returnData := make(map[string]interface{})

	returnData["username"] = user.Username
	returnData["uid"] = auth.Uid(ctx)
	returnData["check"] = auth.Check(ctx)

	return returnData, nil
}
